﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Infragistics.WebUI.WebSchedule;
using TBA.PGB.Common;
using TBA.PGB.DAO;
using TBA.PGB.DAO.AZREntity.Entity;
using TBA.PGB.DAO.AZREntity.Manager;
using TBA.PGB.DAO.DBEntity;
using TBA.PGB.Business;

public partial class secure_zk_PGB_Assignment_AddIB_RelatedInformation : PGBLiveBaseWebPage
{
    private System.IFormatProvider frmt;

    protected void Page_Load(object sender, EventArgs e)
    {
        Nav = (Navigatie)Session["Navigatie"];

        base.RequiredRole = "pgb_base";
        base.RunSecurityCheck();

        frmt = new System.Globalization.CultureInfo("nl-NL", true);

        if (!IsPostBack)
        {
            LoadStepPage(StepType.Step2);
        }
    }

    #region private method
    /// <summary>
    /// The list of step page
    /// </summary>
    private enum StepType
    {
        Step2,
        Step3,
        Step4
    }

    /// <summary>
    /// Load the step by StepType
    /// </summary>
    /// <param name="st"></param>
    private void LoadStepPage(StepType st)
    {
        try
        {
            switch (st)
            {
                case StepType.Step2:
                    Panel_Step2.Visible = true;
                    Panel_Step3.Visible = false;
                    Panel_Step4.Visible = false;
                    form1.DefaultButton = clientInfo_btn_Next.ID;
                    LoadStep2SourceDatas();
                    break;
                case StepType.Step3:
                    Panel_Step2.Visible = false;
                    Panel_Step3.Visible = true;
                    Panel_Step4.Visible = false;
                    form1.DefaultButton = indication_btn_Next.ID;
                    LoadStep3SourceDatas();
                    break;
                case StepType.Step4:
                    Panel_Step2.Visible = false;
                    Panel_Step3.Visible = false;
                    Panel_Step4.Visible = true;
                    form1.DefaultButton = btn_Save.ID;
                    LoadStep4SourceDatas();
                    break;
                default:
                    Panel_Step2.Visible = true;
                    Panel_Step3.Visible = false;
                    Panel_Step4.Visible = false;
                    break;
            }
        }
        catch (Exception ex)
        {
            throw ex;
            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Error", "parent.resultaat.location.href = '../../../../CustomErrors/GenericErrorPage.aspx'", true);
            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Error Msg", "alert('" + ex.ToString() + "');", true);
        }
    }

    /// <summary>
    /// Bind the source datas of dropdownlists
    /// </summary>
    /// <param name="datasource"></param>
    /// <param name="ddlist"></param>
    private void bindLists(Dictionary<String, String> datasource, DropDownList ddlist)
    {
        ddlist.Items.Clear();

        foreach (String key in datasource.Keys)
        {
            ddlist.Items.Add(new ListItem(datasource[key], key));
        }
    }

    private void SetNavigatie(EHoofdNavigatie hoofdNavigatie)
    {
        Nav.HoofdNavigatie = hoofdNavigatie;
        Session["Navigatie"] = Nav;
    }

    private void ClearTempSessions()
    {
        Session["ClientID"] = null;
        Session["IBManuallyBSN"] = null;
    }

    private void ModalPopupFunction(String targetID)
    {
        mpe.Enabled = true;
        ModalPanel1.Visible = true;
        mpe.TargetControlID = targetID;
        //Registering the server-side Postback function on the button 
        //that in the Modal-Popup Screen.
        btn_Yes.OnClientClick = "__doPostBack('" + this.btn_Yes.ClientID + "', '')";
        btn_No.OnClientClick = "__doPostBack('" + this.btn_No.ClientID + "', '')";
        //Page.ClientScript.RegisterStartupScript(this.GetType(), "key", "launchModal();", true);
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key", "launchModal();", true);
    }

    private void CancelBacktoStep1()
    {
        ClearTempSessions();

        //LoadStepPage(StepType.Step2);
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "IB Adding", "parent.resultaat.location.href = 'CheckBSN.aspx'", true);
        SetNavigatie(EHoofdNavigatie.PGBToevoegenClienIB);
    }

    /// <summary>
    /// The action of "Yes" button that in the Modal pop-up screen
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Yes_Click(object sender, EventArgs e)
    {
        CancelBacktoStep1();
    }

    protected void btn_No_Click(object sender, EventArgs e)
    {
        mpe.Enabled = false;
        ModalPanel1.Visible = false;
    }
    #endregion

    #region Step 2

    #region Load Step 2 Datas
    private void LoadStep2SourceDatas()
    {
        LoadDefaultValues();
        LoadClientandAddress();
        //LoadAgeDuration();
        //Geboortedatum.CustomerMinDate = DateTime.Now.AddYears(-120);

        Naam1.Focus();
    }

    private void LoadDefaultValues()
    {
        Naamcode1.Waarde = "1";
        Naamcode2.Waarde = "0";
        Naamcode3.Waarde = "1";
        Geslacht.Waarde = "1";
        Leefeenheid.Waarde = "9";

        codeland.Waarde = "NL";

        if (new Guid(Convert.ToString(Session["ClientID"])) != new Guid())
        {
            soortadres.Enabled = false;
        }
        //ddl_1grondslag.Items.RemoveAt(1);
    }

    private void LoadClientandAddress()
    {
        //Load the basic client informations
        BSN.Enabled = false;
        BSN.Waarde = Convert.ToString(Session["IBManuallyBSN"]).Length == 0 ? String.Empty : Convert.ToString(Session["IBManuallyBSN"]);

        ddl_ClientType.Enabled = new Guid(Convert.ToString(Session["ClientID"])) == new Guid() ? true : false;

        Client client = new Client(new Guid(Convert.ToString(Session["ClientID"])));

        if (new Guid(Convert.ToString(Session["ClientID"])) != new Guid())
        {
            //Client can be obtained from the navigation object.
            client = ViewState["PageClient"] == null ? ClientManager.GetClient(new Guid(Convert.ToString(Session["ClientID"])), Nav.User.ConnString)
                : (ViewState["PageClient"] as Client);
            //string artikel60dat = IndicatiebesluitManager.GetArtikel60Datum(nav.Client.GeselecteerdIndicatiebesluitID, nav.User.ConnString);
            LoadClient(client);
            LoadAddress(client);
        }
        else if (ViewState["PageClient"] != null)
        {
            client = ViewState["PageClient"] as Client;
            LoadClient(client);
            LoadAddress(client);
        }
    }

    private void ClearStep2Inputs()
    {
        String value = String.Empty;
        //ddl_ClientType.SelectedValue = Convert.ToInt32(client.PGBClientType).ToString();
        Naam1.Waarde = value;
        Voorvoegsel1.Waarde = value;
        Voorletters.Waarde = value;
        Naamcode1.Waarde = "1";
        Naam2.Waarde = value;
        Voorvoegsel2.Waarde = value;
        Naamcode2.Waarde = "0";
        Naamcode3.Waarde = "1";
        Geboortedatum.Text = value;
        Geslacht.Waarde = "1";
        Burgerlijkestaat.Waarde = value;
        //UZOVInummer.Waarde = client.UZOVInummer;
        Verzekerdenummer.Waarde = value;
        Leefeenheid.Waarde = "9";

        HF_AddressID.Value = value;
        soortadres.Enabled = true;
        soortadres.Waarde = value;

        codeland.Waarde = "NL";
        huisnummer.Waarde = value;
        huisnummertoevoeging.Waarde = value;
        postcode.Waarde = value;

        straatnaam.Waarde = value;
        telefoonnummer1.Waarde = value;
        woonplaats.Waarde = value;
    }

    private void LoadClient(Client client)
    {
        ddl_ClientType.SelectedValue = Convert.ToInt32(client.PGBClientType).ToString();
        Naam1.Waarde = client.Naam01;
        Voorvoegsel1.Waarde = client.Voorvoegsel01;
        //Voorletters.Waarde = client.Voorletters;
        Voorletters.Waarde = client.Voorletters.Replace(".", "");
        Naamcode1.Waarde = client.Naamcode01;
        Naam2.Waarde = client.Naam02;
        Voorvoegsel2.Waarde = client.Voorvoegsel02;
        Naamcode2.Waarde = client.Naamcode02;
        Naamcode3.Waarde = (client.Naamcode03 == "1" ? "1" : client.Naamcode03);
        Geboortedatum.Text = client.Geboortedatum;
        Geslacht.Waarde = client.Geslacht.Code;
        Burgerlijkestaat.Waarde = client.Burgerlijkestaat.Code;
        //UZOVInummer.Waarde = client.UZOVInummer;
        Verzekerdenummer.Waarde = client.Verzekerdennummer;
        Leefeenheid.Waarde = ((client.Leefeenheid.Code) == String.Empty ? "9" : client.Leefeenheid.Code);
    }

    /// <summary>
    /// Load the address informations of the client
    /// </summary>
    /// <param name="client"></param>
    private void LoadAddress(Client client)
    {
        Adres adres = ViewState["PageAddress"] == null ?
            AddressHandler.getAdredByClientID(client.ClientID, Nav.User.ConnString) : (ViewState["PageAddress"] as Adres);

        if (adres != null)
        {
            HF_AddressID.Value = adres.AdresID.ToString();
            soortadres.Waarde = adres.SoortAdres.Code;

            codeland.Waarde = (adres.CodeLand == "NL" ? "NL" : adres.CodeLand);
            huisnummer.Waarde = (adres.Huisnummer == 0 ? String.Empty : adres.Huisnummer.ToString());
            huisnummertoevoeging.Waarde = adres.HuisnummerToevoeging;
            postcode.Waarde = adres.Postcode;

            straatnaam.Waarde = adres.Straatnaam;
            telefoonnummer1.Waarde = adres.Telefoonnummer01;
            woonplaats.Waarde = adres.WoonplaatsNaam;
        }

        ViewState["OrignalAddress"] = adres;

        ViewState["PageClient"] = client;
        //nav.Client = client;
    }

    private void LoadAgeDuration()
    {
        ///Set the duration of birthday by the Client Type
        ///BJZ: younger than 18
        //if (ddl_ClientType.SelectedValue == "1")
        //{
        //    Geboortedatum.CustomerMaxDate = DateTime.Now;
        //    Geboortedatum.CustomerMinDate = DateTime.Now.AddYears(-18);
        //}
        //else if (ddl_ClientType.SelectedValue == "2")
        //{
        //    Geboortedatum.CustomerMaxDate = DateTime.Now.AddYears(-18);
        //    Geboortedatum.CustomerMinDate = new DateTime(1753, 1, 1);
        //}
    }

    private void ChangeStep2InputsStatus(Boolean status)
    {
        //Client informations
        ddl_ClientType.Enabled = status;
        Naam1.Enabled = status;
        Voorvoegsel1.Enabled = status;
        Voorletters.Enabled = status;
        Naamcode1.Enabled = status;
        Naam2.Enabled = status;
        Voorvoegsel2.Enabled = status;
        Naamcode2.Enabled = status;
        Naamcode3.Enabled = status;
        Geslacht.Enabled = status;
        Geboortedatum.Enabled = status;
        Burgerlijkestaat.Enabled = status;
        Verzekerdenummer.Enabled = status;
        Leefeenheid.Enabled = status;

        //Address informations
        soortadres.Enabled = status;
        huisnummer.Enabled = status;
        huisnummertoevoeging.Enabled = status;
        postcode.Enabled = status;
        straatnaam.Enabled = status;
        woonplaats.Enabled = status;
        codeland.Enabled = status;
        telefoonnummer1.Enabled = status;
    }
    #endregion

    #region Step 2 Buttons Actions
    protected void clientInfo_btn_Cancel_Click(object sender, EventArgs e)
    {
        //ModalPopupFunction(clientInfo_btn_Cancel.ID);
        CancelBacktoStep1();
    }

    protected void ddl_ClientType_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Geboortedatum.Waarde = String.Empty;

        //if (((DropDownList)sender).SelectedValue == "1")
        //{
        //    Geboortedatum.CustomerMaxDate = DateTime.Now;
        //    Geboortedatum.CustomerMinDate = DateTime.Now.AddYears(-18);
        //}
        //else if (((DropDownList)sender).SelectedValue == "2")
        //{
        //    Geboortedatum.CustomerMaxDate = DateTime.Now.AddYears(-18);
        //    Geboortedatum.CustomerMinDate = DateTime.Now.AddYears(-120);
        //}
    }

    private void SaveDatasofStep2()
    {
        Client pageClient = ViewState["PageClient"] == null ? new Client(new Guid()) : (ViewState["PageClient"] as Client);

        //Check the birthday whether be changed
        if (ViewState["PageClient"] != null)
        {
            if (pageClient.Geboortedatum != (Geboortedatum.Text.Trim() == String.Empty
                ? "0" : DateTime.Parse(Geboortedatum.Text.Trim()).ToString("dd-MM-yyyy")))
            {
                ViewState["BIRTHDAYCHANGED"] = true;
            }
        }

        ViewState["PageAddress"] = generatePageAdres();

        //Save Client Informations
        pageClient.Burgerservicenummer = Convert.ToString(Session["IBManuallyBSN"]).Length == 0 ? String.Empty : Convert.ToString(Session["IBManuallyBSN"]);
        pageClient.PGBClientType = (ClientType)Convert.ToInt32(ddl_ClientType.SelectedValue.Trim().ToString());

        //nav.Client.ClientID = nav.Client.ClientID == new Guid() ? Guid.NewGuid() : nav.Client.ClientID;
        pageClient.Naam01 = Naam1.Waarde.ToString().Trim();
        pageClient.Voorvoegsel01 = Voorvoegsel1.Waarde.ToString().Trim();
        pageClient.Voorletters = Voorletters.Waarde.ToString().Trim();
        pageClient.Naamcode01 = Naamcode1.Waarde.ToString().Trim();
        pageClient.Naam02 = Naam2.Waarde.ToString().Trim();
        pageClient.Voorvoegsel02 = Voorvoegsel2.Waarde.ToString().Trim();
        pageClient.Naamcode02 = Naamcode2.Waarde.ToString().Trim();
        pageClient.Naamcode03 = Naamcode3.Waarde.ToString().Trim();
        pageClient.Geslacht = new CodelijstGegeven(Geslacht.Waarde);
        pageClient.Geboortedatum = (Geboortedatum.Text.Trim() == String.Empty 
            ? "0" : DateTime.Parse(Geboortedatum.Text.Trim()).ToString("dd-MM-yyyy"));

        pageClient.Burgerlijkestaat = new CodelijstGegeven(Burgerlijkestaat.Waarde);
        pageClient.Verzekerdennummer = Verzekerdenummer.Waarde.ToString().Trim();
        pageClient.Leefeenheid = new CodelijstGegeven(Leefeenheid.Waarde);
        pageClient.MutatieDatum = DateTime.Now.ToString("dd-MM-yyyy");

        pageClient.ZorgkantoorID = new Guid(Nav.User.ZorgkantoorID);

        if (ViewState["PageClient"] == null)
        {
            ViewState["PageClient"] = pageClient;
        }
    }

    private Boolean ValidateClientName2()
    {
        Boolean result = true;

        if (Naamcode2.Waarde == "2" && Naam2.Waarde.Trim().Length == 0)
        {
            ltl_Name2msg.Text = "<style=\"color:red;\">Als NAAM CLIENT (02) (NAM196) gevuld is, mag NAAM CODE/ NAAMGEBRUIK (02) (COD701) uitsluitend de waarde 2.</style>";
        }
        //else if(Naamcode2.Waarde == "0" && Naa)
        //{
        //}
        return result;
    }

    protected void clientInfo_btn_Previous_Click(object sender, EventArgs e)
    {
        SaveDatasofStep2();
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Manually add IB", "parent.resultaat.location.href = 'CheckBSN.aspx?ClearSession=1'", true);
        SetNavigatie(EHoofdNavigatie.PGBToevoegenClienIB);
        //LoadStepPage(StepType.Step1);
    }

    protected void clientInfo_btn_Next_Click(object sender, EventArgs e)
    {
        //if (ValidateClientName2())
        if (Page.IsValid)
        {
            SaveDatasofStep2();
            LoadStepPage(StepType.Step3);
        }
    }
    #endregion

    #endregion

    #region Step 3

    #region Load Step 3 Datas
    private void LoadStep3SourceDatas()
    {
        ltl_Info.Text = String.Empty;

        LoadStep3Inputs();

        //if (ViewState["PAGEINDICATION"] == null)
        //{
        //    LoadExZZPCodes();
        //}
        //ClearStep3Values();
        //updp_Step3.FindControl("txt_besluitnummer").Focus();        
    }

    private void ClearStep3Values()
    {
        txt_Aanvraagnummer.Text = String.Empty;
        WDC_IndicationDate.Text = String.Empty;
        WDC_ReceiveDate.Text = String.Empty;
        WDC_StartDate.Text = String.Empty;
        WDC_EndDate.Text = String.Empty;
    }

    private void LoadStep3Inputs()
    {
        txt_BSN.Text = (ViewState["PageClient"] as Client).Burgerservicenummer;

        //WDC_IndicationDate.MaxDate = DateTime.Now;
        //WDC_IndicationDate.MinDate = new DateTime(1753, 1, 1);

        LoadStep3DropdownLists();

        if (ViewState["PAGEINDICATION"] != null)
        {
            Indicatiebesluit pageIndication = (Indicatiebesluit)ViewState["PAGEINDICATION"];
            //chk_AdditionalZZPs.Checked = pageIndication.SecondZZPStartDate == null ? false : true;
            chk_AdditionalZZPs.Checked = ViewState["PAGEIBZZPS"] == null ?
                false : (((List<IBZZP>)ViewState["PAGEIBZZPS"]).Count > 1 ? true : false);
        }
        else
        {
            chk_AdditionalZZPs.Checked = false;
        }

        Change2ndZZPValidationStatus(chk_AdditionalZZPs.Checked);
        //LoadExZzpCodes();

        if (ddl_besluitnummer.SelectedValue == "[Geen]")
        {
            LoadExistIndicationInfos(String.Empty, true);
            ChangeStep3InputsStatus(true);
            txt_besluitnummer.Visible = true;
        }
        else
        {
            LoadExistIndicationInfos(ddl_besluitnummer.SelectedValue, false);
            ChangeStep3InputsStatus(false);
            txt_besluitnummer.Visible = false;
        }
    }

    private void LoadStep3DropdownLists()
    {
        //Bind Care offices datas
        switch ((ViewState["PageClient"] as Client).PGBClientType)
        {
            case ClientType.Manually:
                lbl_OfficeList.InnerText = "Hoofdkantoor BJZ";
                lbl_Aanvraagnummer.Visible = false;
                txt_Aanvraagnummer.Visible = false;
                bindLists(IBManuallyHandler.GetBJZOffices(Nav.User.ConnString), ddl_Office);
                break;

            case ClientType.AZRLive:
                lbl_OfficeList.InnerText = "Code Indicatieorgaan";
                lbl_Aanvraagnummer.Visible = true;
                txt_Aanvraagnummer.Visible = true;

                //ChangeAanvraagnummerValidationStatus(true);
                bindLists(IBManuallyHandler.GetCIZOffices(Nav.User.ConnString), ddl_Office);
                break;

            default:
                break;
        }

        //Bind indication number datas
        bindLists(IBManuallyHandler.GetIndicationNumbers(txt_BSN.Text.ToString().Trim(), Nav.User.ConnString), ddl_besluitnummer);
        ddl_besluitnummer.Items.Add("[Geen]");
        ddl_besluitnummer.SelectedValue = ViewState["PAGEINDICATION"] == null ?
            "[Geen]" :
            (txt_besluitnummer.Visible ? "[Geen]" : ((Indicatiebesluit)(ViewState["PAGEINDICATION"])).IndicatiebesluitID.ToString());

        //Bind basis datas
        SetFirstGrondslagsSource();
        bindLists(IBManuallyHandler.GetGrondslags(null, Nav.User.ConnString), ddl_2grondslag);

        //Bind ZZP code datas
        ddl_zzpCode.Items.Clear();

        Dictionary<String, String> datasource = IBManuallyHandler.GetZZPCodes(Nav.User.ConnString);
        ddl_zzpCode.Items.Add(new ListItem("[Geen]", "-1"));
        ddl_2ndZZPCode.Items.Add(new ListItem("[Geen]", "-1"));

        foreach (String key in datasource.Keys)
        {
            ddl_zzpCode.Items.Add(new ListItem(datasource[key], key));
            ddl_2ndZZPCode.Items.Add(new ListItem(datasource[key], key));
        }
    }

    private void SetFirstGrondslagsSource()
    {
        bindLists(IBManuallyHandler.GetGrondslags(null, Nav.User.ConnString), ddl_1grondslag);

        if (ddl_1grondslag.Items.Count > 0)
        {
            ddl_1grondslag.Items.RemoveAt(0);
        }
    }

    private void LoadExZzpCodes()
    {
        RFV_1stZZPEndDate.EnableClientScript = chk_AdditionalZZPs.Checked;
        RFV_2ndZZPStartDate.EnableClientScript = chk_AdditionalZZPs.Checked;

        //tr_1stZZPDates.Visible = chk_AdditionalZZPs.Checked;
        //tr_2ndZZP.Visible = chk_AdditionalZZPs.Checked;
        //tr_2ndZZPDates.Visible = chk_AdditionalZZPs.Checked;

        if (chk_AdditionalZZPs.Checked)
        {
            bindLists(IBManuallyHandler.GetZZPCodes(Nav.User.ConnString), ddl_2ndZZPCode);
        }

        LoadStep3Durations();
    }

    private void ChangeAanvraagnummerValidationStatus(bool Status)
    {
        //RFV_Aanvraagnummer.EnableClientScript = Status;
        //REV_Aanvraagnummer.EnableClientScript = Status;
        RFV_Aanvraagnummer.Enabled = Status;
        REV_Aanvraagnummer.Enabled = Status;
    }

    private void ChangeBesluitnummervalidationStatus(Boolean status)
    {
        REV_Besluitnummer.EnableClientScript = status;
        RFV_Besluitnummer.EnableClientScript = status;

        REV_Besluitnummer.Enabled = status;
        RFV_Besluitnummer.Enabled = status;
    }

    private void ChangeStep3InputsStatus(Boolean status)
    {
        ddl_Office.Enabled = status;
        //ddl_besluitnummer.Enabled = status;
        txt_besluitnummer.Enabled = status;
        txt_Aanvraagnummer.Enabled = status;
        WDC_ReceiveDate.Enabled = status;
        WDC_IndicationDate.Enabled = status;
        WDC_StartDate.Enabled = status;
        WDC_EndDate.Enabled = status;
        ddl_1grondslag.Enabled = status;
        ddl_2grondslag.Enabled = status;
        ddl_zzpCode.Enabled = status;
        ddl_ZZPType.Enabled = ddl_zzpCode.SelectedValue == "-1" ? false : status;
        chk_AdditionalZZPs.Enabled = status;

        if (chk_AdditionalZZPs.Checked)
        {
            WDC_1stZZPEndDate.Enabled = status;
            ddl_2ndZZPCode.Enabled = status;
            WDC_2ndZZPStartDate.Enabled = status;
            ddl_2ndZZPType.Enabled = ddl_2ndZZPCode.SelectedValue == "-1" ? false : status;
        }
    }

    private void SetTypeDDLStatus(DropDownList page_ddl_zzpCode, DropDownList page_ddl_zzpType)
    {
        page_ddl_zzpType.Enabled = page_ddl_zzpCode.SelectedValue == "-1" ? false : true;
    }

    private void Change2ndZZPValidationStatus(Boolean status)
    {
        RFV_1stZZPEndDate.Enabled = status;
        CFV_1stZZPDate.Enabled = status;
        RFV_2ndZZPStartDate.Enabled = status;
        CFV_2ndZZPStartDate.Enabled = status;
        CompareValidator_ZZPCode.Enabled = status;
    }
    #endregion

    #region Validated Step 3 Datas
    private void validateGrondslag(DropDownList ddlList, DropDownList ddlList_selected, String original_SV)
    {
        //bindLists(IBManuallyHandler.GetGrondslags(ddlList_selected.SelectedValue, nav.User.ConnString), ddlList);

        //if (ddlList.Items.FindByValue(original_SV) != null)
        //{
        //    ddlList.SelectedValue = original_SV;
        //}
    }

    private void validateZZP(DropDownList ddlList, DropDownList ddlList_selected, String original_ZZPCode)
    {
        //bindLists(IBManuallyHandler.GetZZPCodes(ddlList_selected.SelectedValue, nav.User.ConnString), ddlList);

        //if (ddlList.Items.FindByValue(original_ZZPCode) != null)
        //{
        //    ddlList.SelectedValue = original_ZZPCode;
        //}
    }

    private void LoadStep3Durations()
    {
        if (chk_AdditionalZZPs.Checked)
        {
            //WDC_1stZZPEndDate.MinDate = DateTime.Parse(WDC_StartDate.Value.ToString());
            //WDC_2ndZZPStartDate.MinDate = DateTime.Parse(WDC_StartDate.Value.ToString());

            //WDC_1stZZPEndDate.MaxDate = DateTime.Parse(WDC_EndDate.Value.ToString());
            //WDC_2ndZZPStartDate.MaxDate = DateTime.Parse(WDC_EndDate.Value.ToString());
            //Load the Date_labels
            //WDC_1stZZPStartDate.Value = DateTime.Parse(WDC_StartDate.Value.ToString());
            label_zzp1_startDate.Text = WDC_StartDate.Text != String.Empty ? DateTime.Parse(WDC_StartDate.Text.Trim()).ToString("dd-MM-yyyy") : String.Empty;
            label_zzp2_endDate.Text = WDC_EndDate.Text != String.Empty ? DateTime.Parse(WDC_EndDate.Text.Trim()).ToString("dd-MM-yyyy") : String.Empty;
            //WDC_2ndZZPEndDate.Value = DateTime.Parse(WDC_EndDate.Value.ToString());
        }
    }
    #endregion

    #region Step 3 Dropdownlists(/DateChooser) Actions
    protected void ddl_1grondslag_SelectedIndexChanged(object sender, EventArgs e)
    {
        //validateGrondslag(ddl_2grondslag, (DropDownList)sender, ddl_2grondslag.SelectedValue);
    }

    protected void ddl_2grondslag_SelectedIndexChanged(object sender, EventArgs e)
    {
        //validateGrondslag(ddl_1grondslag, (DropDownList)sender, ddl_1grondslag.SelectedValue);
    }

    private void ClearChangedViewStates()
    {
        ViewState["PageFuncs"] = null;
        ViewState["PAGEIBZZPS"] = null;
        ViewState["PAGEZTWZZPS"] = null;
    }

    protected void ddl_zzpCode_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClearChangedViewStates();
        //if (chk_AdditionalZZPs.Checked)
        //{
        //    validateZZP(ddl_2ndZZPCode, (DropDownList)sender, ddl_2ndZZPCode.SelectedValue);
        //}
    }

    protected void ddl_ZZPType_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClearChangedViewStates();
    }

    protected void ddl_2ndZZPType_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClearChangedViewStates();
    }

    protected void ddl_2ndZZPCode_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClearChangedViewStates();
        //if (chk_AdditionalZZPs.Checked)
        //{
        //    validateZZP(ddl_zzpCode, (DropDownList)sender, ddl_zzpCode.SelectedValue);
        //}
    }

    private void set_enabled_status_ddl_zzpCode()
    {
        if (WDC_StartDate.Text.Trim() != String.Empty &&
            WDC_EndDate.Text.Trim() != String.Empty)
        {
            ddl_zzpCode.Enabled = true;
        }
        else
        {
            ddl_zzpCode.Enabled = false;
        }
    }

    protected void ddl_besluitnummer_SelectedIndexChanged(object sender, EventArgs e)
    {
        ViewState["PageFuncs"] = null;

        if (((DropDownList)sender).SelectedValue == "[Geen]")
        {
            ViewState["PAGEINDICATION"] = null;
            chk_AdditionalZZPs.Checked = false;
            //LoadExZZPCodes();
            LoadExistIndicationInfos(String.Empty, false);
            ChangeStep3InputsStatus(true);
            txt_besluitnummer.Visible = true;
        }
        else
        {
            LoadExistIndicationInfos(((DropDownList)sender).SelectedValue, false);
            ChangeStep3InputsStatus(false);
            txt_besluitnummer.Visible = false;
        }
    }

    /// <summary>
    /// Load the existed indication's information by the ddl_besluitnummer
    /// </summary>
    /// <param name="indicationID"></param>
    /// <param name="inputsStatus"></param>
    private void LoadExistIndicationInfos(String indicationID, Boolean inputsStatus)
    {
        //txt_besluitnummer.Visible = inputsStatus;

        ChangeBesluitnummervalidationStatus(indicationID == String.Empty ? true : false);

        using (Indicatiebesluit indication = inputsStatus ?
                (ViewState["PAGEINDICATION"] == null ? (new Indicatiebesluit(new Guid())) : (Indicatiebesluit)ViewState["PAGEINDICATION"]) :
                indicationID == String.Empty ? (new Indicatiebesluit(new Guid())) : IBManuallyHandler.GetIndicationInfoByID(new Guid(indicationID.Trim()), Nav.User.ConnString))
        {
            txt_Aanvraagnummer.Text = txt_Aanvraagnummer.Visible ? indication.Aanvraagnummer : String.Empty;
            txt_besluitnummer.Text = txt_besluitnummer.Visible ? indication.Besluitnummer : String.Empty;

            //if (indication.ReceiveDate != new DateTime())
            //{
            WDC_ReceiveDate.Text = indication.ReceiveDate != new DateTime() ? indication.ReceiveDate.ToString("dd-MM-yyyy") : String.Empty;
            //}

            WDC_IndicationDate.Text = indication.DatumAfgifte != null && indication.DatumAfgifte.Value != new DateTime() 
                ? indication.DatumAfgifte.Value.ToString("dd-MM-yyyy") : String.Empty;
            WDC_StartDate.Text = indication.DatumIngang != null && indication.DatumIngang.Value != new DateTime()
                ? indication.DatumIngang.Value.ToString("dd-MM-yyyy") : String.Empty;
            WDC_EndDate.Text = indication.DatumEindeGeldigheid != null && indication.DatumEindeGeldigheid.Value != new DateTime()
                ? indication.DatumEindeGeldigheid.Value.ToString("dd-MM-yyyy"):String.Empty;

            List<IBZZP> zzpsList = ViewState["PAGEIBZZPS"] == null ?
                IBManuallyHandler.GetZZPsforStep4(indication.IndicatiebesluitID, Nav.User.ConnString) : (List<IBZZP>)ViewState["PAGEIBZZPS"];

            if (indication.IndicatiebesluitID != new Guid())
            {
                //chk_AdditionalZZPs.Checked = indication.SecondZZPStartDate == null ? false : true;
                ///load the extra zzp inputs by the zzps of this indication
                chk_AdditionalZZPs.Checked = zzpsList.Count > 1 ? true : false;
                LoadExZzpCodes();
            }

            if (indication.EersteGrondslag != null)
            {
                ddl_1grondslag.SelectedValue = indication.EersteGrondslag.ToString().Trim();
            }
            //else
            //{
            //    ddl_1grondslag.SelectedValue = "00";
            //}

            if (indication.TweedeGrondslag != null)
            {
                ddl_2grondslag.SelectedValue = indication.TweedeGrondslag.ToString().Trim();
            }
            else
            {
                ddl_2grondslag.SelectedValue = "00";
            }

            //Load ZZP for viewsate["PageIBZZP"]
            ddl_zzpCode.SelectedValue = zzpsList.Count > 0 ? zzpsList[0].ZZPCode.ToString().Trim() : "-1";

            if (chk_AdditionalZZPs.Checked)
            {
                WDC_1stZZPEndDate.Text = zzpsList[0].EndDate.ToString("dd-MM-yyyy");
                WDC_2ndZZPStartDate.Text = zzpsList[1].StartDate.ToString("dd-MM-yyyy");

                ddl_2ndZZPCode.SelectedValue = zzpsList.Count > 1 ? zzpsList[1].ZZPCode.ToString().Trim() : "-1";
            }

            if (indication.Besluitnummer != null)
            {
                ViewState["PAGEINDICATION"] = indication;
            }
        }
    }
    #endregion

    #region Step 3 Buttons Actions
    protected void chk_AdditionalZZPs_CheckedChanged(object sender, EventArgs e)
    {
        //if ((WDC_StartDate.Value == null || WDC_StartDate.Value.ToString() == "")
        //   || (WDC_EndDate.Value == null || WDC_EndDate.Value.ToString() == "")
        //   || (WDC_ReceiveDate.Value == null || WDC_ReceiveDate.Value.ToString() == "")
        //   || (WDC_IndicationDate.Value == null || WDC_IndicationDate.Value.ToString() == "")
        //   || (txt_besluitnummer.Text == null || txt_besluitnummer.Text == string.Empty)
        //   || (txt_Aanvraagnummer.Visible && (txt_Aanvraagnummer.Text == null || txt_Aanvraagnummer.Text == string.Empty))
        //    )
        //{
        //    ((CheckBox)sender).Checked = false;
        //}

        //ChangeAanvraagnummerValidationStatus((ViewState["PageClient"] as Client).PGBClientType == ClientType.Manually ? false : true);
        ////if (((CheckBox)sender).Checked)
        ////{
        //Page.Validate();
        ////}

        //LoadExZZPCodes();
        ////LoadStep3Durations();

        //if (!((CheckBox)sender).Checked)
        //{
        //    WDC_1stZZPEndDate.Value = String.Empty;
        //    WDC_2ndZZPStartDate.Value = String.Empty;

        //    if (ddl_zzpCode.Items.FindByValue("-1") == null)
        //    {
        //        ddl_zzpCode.Items.Insert(0, new ListItem("[Geen]", "-1"));
        //    }
        //}
        //else
        //{
        //    ddl_zzpCode.Items.Remove(new ListItem("[Geen]", "-1"));
        //    ddl_ZZPType.Enabled = true;
        //    ddl_2ndZZPType.Enabled = true;
        //}
    }

    protected void indication_btn_Cancel_Click(object sender, EventArgs e)
    {
        //ModalPopupFunction(indication_btn_Cancel.ID);
        CancelBacktoStep1();
    }

    protected void indication_btn_Previous_Click(object sender, EventArgs e)
    {
        //if (ViewState["PAGEINDICATION"] == null)
        //{
        ViewState["PAGEINDICATION"] = SaveDatasofStep3();
        //}

        LoadStepPage(StepType.Step2);
        //refill the birthday
        //Geboortedatum.Waarde = (ViewState["PageClient"] as Client).Geboortedatum;
    }

    private Indicatiebesluit SaveDatasofStep3()
    {
        Indicatiebesluit _pageIndication = ViewState["PAGEINDICATION"] == null ?
                (new Indicatiebesluit(ddl_besluitnummer.SelectedValue == "[Geen]" ?
                    Guid.NewGuid() : new Guid(ddl_besluitnummer.SelectedValue.Trim())))
                : new Indicatiebesluit((ViewState["PAGEINDICATION"] as Indicatiebesluit).IndicatiebesluitID);

        _pageIndication.ClientID = (ViewState["PageClient"] as Client).ClientID;

        if ((ViewState["PageClient"] as Client).PGBClientType == ClientType.Manually)
        {
            _pageIndication.BJZOfficeID = Convert.ToInt32(ddl_Office.SelectedValue);
            //TODO: Inserted the default value "1700" as a BJZ client
            _pageIndication.Indicatieorgaan = "1700";
            _pageIndication.Clientnummer = "BJZ" + (ViewState["PageClient"] as Client).Burgerservicenummer;
        }

        if ((ViewState["PageClient"] as Client).PGBClientType == ClientType.AZRLive)
        {
            _pageIndication.Indicatieorgaan = ddl_Office.SelectedValue.Trim().ToString();
        }

        _pageIndication.Aanvraagnummer = txt_Aanvraagnummer.Visible ? txt_Aanvraagnummer.Text.ToString().Trim() : String.Empty;
        _pageIndication.Besluitnummer = ddl_besluitnummer.SelectedValue == "[Geen]" ?
            (txt_besluitnummer.Text.ToString().Trim() == String.Empty ?
                String.Empty : txt_besluitnummer.Text.ToString().Trim())
            : ddl_besluitnummer.SelectedItem.Text.ToString().Trim();
        _pageIndication.EersteGrondslag = ddl_1grondslag.SelectedValue.ToString().Trim();
        _pageIndication.TweedeGrondslag = ddl_2grondslag.SelectedValue.ToString().Trim();

        if (WDC_IndicationDate.Text.Trim() != String.Empty)
        {
            _pageIndication.DatumAfgifte = DateTime.Parse(WDC_IndicationDate.Text.Trim());
        }

        if (WDC_StartDate.Text.Trim() != String.Empty)
        {
            _pageIndication.DatumIngang = DateTime.Parse(WDC_StartDate.Text.Trim());
        }

        if (WDC_EndDate.Text.Trim() != String.Empty)
        {
            _pageIndication.DatumEindeGeldigheid = DateTime.Parse(WDC_EndDate.Text.Trim());
        }
        _pageIndication.UpdatedBy = new Guid(Nav.User.UserID);
        //_pageIndication.Clientnummer = (ViewState["PageClient"] as Client).Clientnummer;
        //_pageIndication.AddingIB = (AddingIBWay)Convert.ToInt32((ViewState["PageClient"] as Client).PGBClientType);
        //_pageIndication.BJZOffice

        //if (ddl_zzpCode.SelectedValue != "-1")
        //{
        //    _pageIndication.ZZP = ddl_zzpCode.SelectedValue.ToString().Trim();

        //    if (_pageIndication.DatumIngang.HasValue)
        //    {
        //        _pageIndication.ZZPStartDate = _pageIndication.DatumIngang.Value;
        //    }

        //    if (chk_AdditionalZZPs.Checked && WDC_1stZZPEndDate.Value != null)
        //    {
        //        _pageIndication.ZZPEndDate = DateTime.Parse(WDC_1stZZPEndDate.Value.ToString());
        //    }
        //    else if (!(chk_AdditionalZZPs.Checked) && WDC_EndDate.Value != null)
        //    {
        //        _pageIndication.ZZPEndDate = DateTime.Parse(WDC_EndDate.Value.ToString());
        //    }
        //}
        ////_pageIndication.ZZPStartDate = DateTime.Parse(WDC_StartDate.Value.ToString());

        //if (chk_AdditionalZZPs.Checked)
        //{
        //    if (ddl_2ndZZPCode.SelectedValue != "-1")
        //    {
        //        _pageIndication.SecondZZP = ddl_2ndZZPCode.SelectedValue.ToString().Trim();

        //        if (WDC_2ndZZPStartDate.Value != null)
        //        {
        //            _pageIndication.SecondZZPStartDate = DateTime.Parse(WDC_2ndZZPStartDate.Value.ToString());
        //        }
        //        //_pageIndication.SecondZZPEndDate = DateTime.Parse(WDC_EndDate.Value.ToString());
        //        _pageIndication.SecondZZPEndDate = _pageIndication.DatumEindeGeldigheid;
        //    }
        //}

        if (WDC_ReceiveDate.Text.Trim() != String.Empty)
        {
            _pageIndication.ReceiveDate = DateTime.Parse(WDC_ReceiveDate.Text.Trim());
        }

        return _pageIndication;
    }

    private IBZZP GetPageZZPRecord(DropDownList page_ddl_zzpCode, DropDownList page_ddl_zzpType,
        TextBox page_wdc_zzpStartDate, TextBox page_wdc_zzpEndDate)
    {
        using (IBZZP ibzzp = new IBZZP())
        {
            ibzzp.IBZZPID = Guid.NewGuid();
            ibzzp.ZZPCode = Convert.ToInt32(page_ddl_zzpCode.SelectedValue);
            ibzzp.StartDate = DateTime.Parse(page_wdc_zzpStartDate.Text.Trim());
            ibzzp.EndDate = DateTime.Parse(page_wdc_zzpEndDate.Text.Trim());
            ibzzp.IBType = new CodelijstGegeven(page_ddl_zzpType.SelectedValue, page_ddl_zzpType.SelectedItem.Text);
            ibzzp.UpdatedBy = new Guid(Nav.User.UserID);

            return ibzzp;
        }
    }

    private List<IBZZP> SaveZZPsofIndication()
    {
        List<IBZZP> ibzzps = new List<IBZZP>();

        if (Convert.ToInt32(ddl_zzpCode.SelectedValue) > -1)
        {
            if (chk_AdditionalZZPs.Checked)
            {
                ibzzps.Add(GetPageZZPRecord(ddl_zzpCode, ddl_ZZPType, WDC_StartDate, WDC_1stZZPEndDate));
                ibzzps.Add(GetPageZZPRecord(ddl_2ndZZPCode, ddl_2ndZZPType, WDC_2ndZZPStartDate, WDC_EndDate));
            }
            else
            {
                ibzzps.Add(GetPageZZPRecord(ddl_zzpCode, ddl_ZZPType, WDC_StartDate, WDC_EndDate));
            }
        }

        ///Generate page ztw zzps
        if (ibzzps.Count > 0)
        {
            List<ZTWZZP> ztwZZPs = new List<ZTWZZP>();

            foreach (IBZZP ibzzp in ibzzps)
            {
                using (ZTWZZP ztwzzp = new ZTWZZP())
                {
                    ztwzzp.ZTWZZPID = Guid.NewGuid();
                    ztwzzp.RelatedIBZZPID = ibzzp.IBZZPID;
                    ztwzzp.ZZPCode = ibzzp.ZZPCode;
                    ztwzzp.StartDate = ibzzp.StartDate;
                    ztwzzp.EndDate = ibzzp.EndDate;
                    ztwzzp.CareOffice = Nav.User.Zorgkantoorcode;
                    ztwzzp.AllocationDate = ztwzzp.StartDate;
                    ztwzzp.UpdatedBy = new Guid(Nav.User.UserID);

                    ztwZZPs.Add(ztwzzp);
                }
            }

            ViewState["PAGEZTWZZPS"] = ztwZZPs;
        }

        return ibzzps;
    }

    protected void indication_btn_Next_Click(object sender, EventArgs e)
    {
        ChangeBesluitnummervalidationStatus(txt_besluitnummer.Visible);
        ChangeAanvraagnummerValidationStatus((ViewState["PageClient"] as Client).PGBClientType == ClientType.Manually ? false : true);

        Change2ndZZPValidationStatus(chk_AdditionalZZPs.Checked);

        if (Page.IsValid)
        {
            Indicatiebesluit indi = SaveDatasofStep3();
            List<IBZZP> zzps = SaveZZPsofIndication();

            ViewState["IndicationStatus"] = chk_AdditionalZZPs.Enabled ? (ViewState["PAGEINDICATION"] == null ? true :
                setIndicationChangedStatus((ViewState["PAGEINDICATION"] as Indicatiebesluit), indi, (ViewState["PAGEIBZZPS"] as List<IBZZP>), zzps)) : false;
            ViewState["PAGEINDICATION"] = indi;
            //SaveDatasofStep3();

            ViewState["PAGEIBZZPS"] = zzps;

            if (ddl_besluitnummer.SelectedValue == "[Geen]")
            {
                ProcessStep3Workflow();
            }
            else
            {
                //ViewState["PageFuncs"] = ViewState["PageFuncs"];
                LoadStepPage(StepType.Step4);
            }
        }
    }

    protected void btn_vltScdZZP_Click(object sender, EventArgs e)
    {
        Page.Validate();
    }

    private Boolean setIndicationChangedStatus(Indicatiebesluit oldIndication, Indicatiebesluit newIndication, List<IBZZP> oldzzps, List<IBZZP> newzzps)
    {
        Boolean result = false;

        if (oldIndication.DatumIngang == newIndication.DatumIngang &&
            oldIndication.DatumEindeGeldigheid == newIndication.DatumEindeGeldigheid &&
            (oldzzps == null ? false : oldzzps.Count == newzzps.Count))
        {
            result = true;
        }
        else
        {
            result = false;
        }

        if (oldzzps != null && oldzzps.Count > 0)
        {
            foreach (IBZZP o_zzp in oldzzps)
            {
                if (o_zzp.ZZPCode == newzzps[oldzzps.IndexOf(o_zzp)].ZZPCode &&
                o_zzp.IBType.Code == newzzps[oldzzps.IndexOf(o_zzp)].IBType.Code &&
                o_zzp.StartDate == newzzps[oldzzps.IndexOf(o_zzp)].StartDate &&
                o_zzp.EndDate == newzzps[oldzzps.IndexOf(o_zzp)].EndDate)
                {
                    result = true;
                    break;
                }
            }
        }

        return result;
    }

    private void ProcessStep3Workflow()
    {
        IBManuallyHandler ibh = new IBManuallyHandler();
        Dictionary<Boolean, String> result = ibh.CheckIBExisted(((Indicatiebesluit)ViewState["PAGEINDICATION"]),
            Nav.User.ConnString, txt_BSN.Text.ToString(), (ViewState["PageClient"] as Client).PGBClientType);

        if (result.ContainsKey(true))
        {
            foreach (KeyValuePair<Boolean, String> kvp in result)
            {
                if (kvp.Key)
                {
                    ltl_Info.Text = "<span style=\"color:Red;\">*" + kvp.Value + "</span>";
                }
            }
        }
        else if (result.ContainsKey(false))
        {
            LoadStepPage(StepType.Step4);
        }
    }
    #endregion

    #endregion

    #region Step 4

    #region private Method
    /// <summary>
    /// Bind the data of function/Activity/Class dropdownlist
    /// </summary>
    /// <param name="pageIndication">The indication which has been loaded form step 3.</param>
    /// <param name="zzpType">The zzp order[Should be removed later.]</param>
    /// <param name="page_ddl_Functie">Webcontrol: dropdownlist of functions</param>
    /// <param name="page_ddl_Activiteit">Webcontrol: dropdownlist of activities</param>
    /// <param name="page_ddl_Klasse">Webcontrol: dropdownlist of classes</param>
    private void LoadStep4DDLists(Indicatiebesluit pageIndication, ZZPType zzpType,
        DropDownList page_ddl_Functie, DropDownList page_ddl_Activiteit, DropDownList page_ddl_Klasse)
    {
        bindLists(IBManuallyHandler.GetFunctions(null, Nav.User.ConnString), page_ddl_Functie);

        bindLists(IBManuallyHandler.GetActivies(page_ddl_Functie.SelectedValue, null, Nav.User.ConnString), page_ddl_Activiteit);

        bindLists(IBManuallyHandler.GetClasses(page_ddl_Functie.SelectedValue, Nav.User.ConnString),
                      page_ddl_Klasse);
    }

    private void LoadStep4Durations(DateTime StartDate, DateTime EndDate,
        TextBox page_WDC_Ingangsdatum, TextBox page_WDC_Endiedatum)
    {
        lbl_indiStartDate.Text = StartDate.ToString("dd-MM-yyyy");
        lbl_indiEndDate.Text = EndDate.ToString("dd-MM-yyyy");
        //TODO:Set in jQuery
        //page_WDC_Ingangsdatum.MinDate = StartDate;
        //page_WDC_Endiedatum.MinDate = StartDate;

        //page_WDC_Ingangsdatum.MaxDate = EndDate;
        //page_WDC_Endiedatum.MaxDate = EndDate;

        //page_WDC_Ingangsdatum.Value = StartDate;
        //page_WDC_Endiedatum.Value = EndDate;
    }

    private void LoadStep4ExtraInformation(DropDownList page_ddl_Functie,
        DropDownList page_ddl_Klasse, DropDownList page_ddl_timeUnit, TextBox page_txt_Number,
        RegularExpressionValidator page_REV_number)
    {
        String selectedFunctionCode = page_ddl_Functie.SelectedValue;
        String selectedClassCode = page_ddl_Klasse.SelectedValue;
        String maxClassCode = page_ddl_Klasse.Items[page_ddl_Klasse.Items.Count - 1].Value;

        page_txt_Number.Text = String.Empty;
        //dbo.[21_Functie].Tijdseenheid is null
        if (selectedFunctionCode == "61" || selectedFunctionCode == "62" || selectedFunctionCode == "71"
            || selectedFunctionCode == "72" || selectedClassCode != maxClassCode)
        {
            page_txt_Number.Enabled = false;
            page_ddl_timeUnit.Enabled = false;
        }
        else
        {
            page_txt_Number.Enabled = true;

            //dbo.[21_Functie].Tijdseenheid = 13; [Day] FK to dbo.[21_Tijdseenheid]
            if (selectedClassCode == "12" || selectedClassCode == "52" || selectedClassCode == "82")
            {
                page_ddl_timeUnit.SelectedValue = "13";
            }

            //dbo.[21_Functie].Tijdseenheid = 04; [Hour] FK to dbo.[21_Tijdseenheid]
            if (selectedClassCode == "11" || selectedClassCode == "21" || selectedClassCode == "31" ||
                selectedClassCode == "41" || selectedClassCode == "51" || selectedClassCode == "81")
            {
                page_ddl_timeUnit.SelectedValue = "04";
            }

            page_ddl_timeUnit.Enabled = false;
        }

        page_REV_number.Enabled = page_txt_Number.Enabled;
        //page_RFV_number.Enabled = page_txt_Number.Enabled;

        setTextboxDisabledColor(page_txt_Number);
    }

    private void LoadStep4InputStatus(Boolean status, Boolean isNewIndication,
        Button page_btn_AddFunc, Button page_UpdateFunc, DropDownList page_ddl_IndicationType)
    {
        page_btn_AddFunc.Enabled = isNewIndication ? status : false;
        page_UpdateFunc.Enabled = isNewIndication ? !status : false;
        page_ddl_IndicationType.Enabled = isNewIndication ? status : false;
        gv_Functions.Enabled = isNewIndication ? status : false;
        btn_Save.Enabled = isNewIndication ? status : false;
    }

    private String getGridviewRowData(GridViewRow gv_FuncSRow, String lbl_Name)
    {
        return ((Label)gv_FuncSRow.FindControl(lbl_Name)).Text;
    }

    private void LoadTransport(CheckBox chk, String functionCode, Boolean? isTransport)
    {
        if (functionCode == "12" || functionCode == "52" || functionCode == "82")
        {
            chk.Visible = true;
            chk.Checked = isTransport == null ? false : isTransport.Value;
        }
        else
        {
            chk.Visible = false;
        }
    }

    private void LoadExtraTimeInputs(String FunctionCode, DropDownList page_ddl_Class,
        Label page_lbl_extraTime, TextBox page_txt_Number, DropDownList page_ddl_timeUnit)
    {
        if (FunctionCode == "61" || FunctionCode == "62" ||
            FunctionCode == "71" || FunctionCode == "72" || page_ddl_Class.SelectedIndex != (page_ddl_Class.Items.Count - 1))
        {
            page_lbl_extraTime.Visible = false;
            page_txt_Number.Visible = false;
            page_ddl_timeUnit.Visible = false;
        }
        else if (page_ddl_Class.SelectedValue != String.Empty)
        {
            page_lbl_extraTime.Visible = true;
            page_txt_Number.Visible = true;
            page_ddl_timeUnit.Visible = true;

            if (page_ddl_Class.SelectedValue.Substring(0, 2) == "KD")
            {
                page_ddl_timeUnit.SelectedValue = "13";
            }
            else
            {
                page_ddl_timeUnit.SelectedValue = "04";
            }
        }
    }

    private void entitledFunctionType(DropDownList page_ddl_Function, DropDownList page_ddl_IndicationType)
    {
        if (page_ddl_Function.SelectedValue == "61" || page_ddl_Function.SelectedValue == "62")
        {
            page_ddl_IndicationType.SelectedValue = "4"; //Only "ZIN"
            page_ddl_IndicationType.Enabled = false;
        }
        else
        {
            page_ddl_IndicationType.Enabled = true;
            page_ddl_IndicationType.SelectedIndex = -1;
        }
    }
    #endregion

    #region Load Function Inputs Datas
    private List<ViewZTWFunction> GetStep4ZtwFunctions(Guid indicationId)
    {
        var funcs = (Boolean)ViewState["IndicationStatus"] ? (ViewState["PageFuncs"] as List<ViewZTWFunction>)
            : IBManuallyHandler.GetFunctionsByIndicationID(indicationId, Nav.User.ConnString);

        if (ddl_zzpCode.SelectedValue != "-1" || chk_AdditionalZZPs.Checked)
        {
            funcs = new List<ViewZTWFunction>();

            var pageibzzps = (List<IBZZP>)ViewState["PAGEIBZZPS"];

            foreach (IBZZP zzp in pageibzzps)
            {
                foreach (ViewZTWFunction func
                    in (List<ViewZTWFunction>)IBManuallyHandler.GetFunctionsByZZP(zzp.ZZPCode, zzp.StartDate, zzp.EndDate, Nav.User.ConnString))
                {
                    func.Leveringsvorm = zzp.IBType;
                    func.ZZPID = ((List<ZTWZZP>)ViewState["PAGEZTWZZPS"]).Find(
                        ztwzzp => ztwzzp.RelatedIBZZPID == zzp.IBZZPID).ZTWZZPID;

                    func.IBZZPID = zzp.IBZZPID;

                    funcs.Add(func);
                }
            }
        }

        ViewState["PageFuncs"] = funcs;

        return funcs;
    }

    private void LoadStep4SourceDatas()
    {
        using (var indi = (Indicatiebesluit)ViewState["PAGEINDICATION"])
        {
            //Load the input controls
            ResetFunctionInputs();
            LoadStep4DDLists(indi, ZZPType.FirstZZP, ddl_Functie, ddl_Activiteit, ddl_Klasse);
            if (indi.DatumIngang != null && indi.DatumEindeGeldigheid != null)
            {
                LoadStep4Durations(indi.DatumIngang.Value, indi.DatumEindeGeldigheid.Value,
                                   jsTxt_FunctionStartDate, jsTxt_FunctionEndDate);
            }

            LoadStep4ExtraInformation(ddl_Functie, ddl_Klasse, ddl_timeUnit,
                txt_Number, REV_number);
            LoadStep4InputStatus(true, (ddl_besluitnummer.SelectedValue == "[Geen]" ? true : false),
                btn_AddFunc, btn_UpdateFunc, ddl_IndicationType);
            LoadTransport(chk_Transport, ddl_Functie.SelectedValue, null);
            LoadExtraTimeInputs(ddl_Functie.SelectedValue, ddl_Klasse, lbl_extraTime, txt_Number, ddl_timeUnit);

            GetStep4ZtwFunctions(indi.IndicatiebesluitID);
            gv_Functions.DataSource = (List<ViewZTWFunction>)ViewState["PageFuncs"];
            gv_Functions.DataBind();
        }
    }

    private void setTextboxDisabledColor(TextBox page_txt_Number)
    {
        if (!page_txt_Number.Enabled)
        {
            page_txt_Number.ControlStyle.BorderColor = System.Drawing.Color.White;
        }
    }
    #endregion

    #region Dropdownlists Actions
    protected void ddl_Functie_SelectedIndexChanged(object sender, EventArgs e)
    {
        Indicatiebesluit SourceIndication = (Indicatiebesluit)ViewState["PAGEINDICATION"];

        bindLists(IBManuallyHandler.GetActivies(((DropDownList)sender).SelectedValue,
            null, Nav.User.ConnString), ddl_Activiteit);

        bindLists(IBManuallyHandler.GetClasses(((DropDownList)sender).SelectedValue,
            Nav.User.ConnString), ddl_Klasse);

        LoadStep4ExtraInformation((DropDownList)sender, ddl_Klasse, ddl_timeUnit,
                txt_Number, REV_number);

        LoadTransport(chk_Transport, ((DropDownList)sender).SelectedValue, null);

        LoadExtraTimeInputs(((DropDownList)sender).SelectedValue, ddl_Klasse, lbl_extraTime, txt_Number, ddl_timeUnit);

        entitledFunctionType(((DropDownList)sender), ddl_IndicationType);

        ChangeStep4InputsStatus(true, jsTxt_FunctionStartDate, jsTxt_FunctionEndDate,
                                    ddl_Functie, ddl_Activiteit, ddl_Klasse, ddl_timeUnit,
                                    txt_Number);
    }

    protected void ddl_Klasse_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadStep4ExtraInformation(ddl_Functie, (DropDownList)sender, ddl_timeUnit,
            txt_Number, REV_number);

        LoadExtraTimeInputs(ddl_Functie.SelectedValue, ((DropDownList)sender), lbl_extraTime, txt_Number, ddl_timeUnit);
    }
    #endregion

    #region Validation Actions
    private bool validatedFuncOverlap(List<ViewZTWFunction> pageFuncList, DateTime startDate, DateTime endDate, String funcCode)
    {
        if (HF_RowIndex.Value.ToString().Trim() == String.Empty)
        {
            return pageFuncList.Exists(delegate(ViewZTWFunction fFunc)
            {
                return fFunc.Functiecode.Code == funcCode
                    && (((fFunc.GewensteStartdatum.CompareTo(startDate) < 0 || fFunc.GewensteStartdatum.CompareTo(startDate) == 0)
                        && (fFunc.GewensteEinddatum.Value.CompareTo(startDate) > 0 || fFunc.GewensteEinddatum.Value.CompareTo(startDate) == 0))
                    || ((fFunc.GewensteEinddatum.Value.CompareTo(endDate) > 0 || fFunc.GewensteEinddatum.Value.CompareTo(endDate) == 0)
                        && (fFunc.GewensteStartdatum.CompareTo(endDate) < 0 || fFunc.GewensteStartdatum.CompareTo(endDate) == 0)));
            });
        }
        else
        {
            return pageFuncList.FindAll(delegate(ViewZTWFunction fFunc)
            {
                return fFunc.Functiecode.Code == funcCode
                    && (((fFunc.GewensteStartdatum.CompareTo(startDate) < 0 || fFunc.GewensteStartdatum.CompareTo(startDate) == 0)
                        && (fFunc.GewensteEinddatum.Value.CompareTo(startDate) > 0 || fFunc.GewensteEinddatum.Value.CompareTo(startDate) == 0))
                    || ((fFunc.GewensteEinddatum.Value.CompareTo(endDate) > 0 || fFunc.GewensteEinddatum.Value.CompareTo(endDate) == 0)
                        && (fFunc.GewensteStartdatum.CompareTo(endDate) < 0 || fFunc.GewensteStartdatum.CompareTo(endDate) == 0)));
            }).Count > 1;
        }
    }

    protected void cstV_Ingangsdatum_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = !validatedFuncOverlap((ViewState["PageFuncs"] == null ? new List<ViewZTWFunction>() : (ViewState["PageFuncs"] as List<ViewZTWFunction>)),
            DateTime.Parse(jsTxt_FunctionStartDate.Text.Trim()), new DateTime(),
            ddl_Functie.SelectedValue);

        if (args.IsValid)
        {
            cstV_Ingangsdatum.ErrorMessage = @"De ingangsdatum is overlappend met toegevoegde functies!";
        }

    }

    protected void cstV_Endiedatum_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = !validatedFuncOverlap((ViewState["PageFuncs"] == null ? new List<ViewZTWFunction>() : (ViewState["PageFuncs"] as List<ViewZTWFunction>)),
            new DateTime(), DateTime.Parse(jsTxt_FunctionEndDate.Text.Trim()),
            ddl_Functie.SelectedValue);

        if (args.IsValid)
        {
            cstV_Endiedatum.ErrorMessage = @"Einddatum is overlappend met toegevoegde functies!";
        }
    }
    #endregion

    #region Buttons Actions
    protected void btn_AddFunc_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            List<ViewZTWFunction> pagefuncList = (ViewState["PageFuncs"] == null ? new List<ViewZTWFunction>() : (ViewState["PageFuncs"] as List<ViewZTWFunction>));

            using (ViewZTWFunction pagefunc = new ViewZTWFunction())
            {
                ViewState["PageFuncs"] = generatePageFunctions(pagefuncList, pagefunc, true,
                    ddl_Functie, chk_Transport, ddl_Activiteit, ddl_Klasse, ddl_timeUnit, ddl_IndicationType,
                    txt_Number, jsTxt_FunctionStartDate, jsTxt_FunctionEndDate);
            }

            gv_Functions.DataSource = pagefuncList;
            gv_Functions.DataBind();
            ResetFunctionInputs();
        }
    }

    private void ResetFunctionInputs()
    {
        bool needReload = false;

        ddl_Functie.Enabled = true;

        if (ddl_Functie.SelectedIndex != 0)
        {
            needReload = true;
        }

        ddl_Functie.SelectedIndex = 0;

        if (needReload)
        {
            ddl_Functie_SelectedIndexChanged(ddl_Functie, new EventArgs());
        }

        ddl_IndicationType.SelectedIndex = 0;
        ddl_Activiteit.SelectedIndex = 0;
        ddl_Klasse.SelectedIndex = 0;

        //TODO: Check in jQuery
        //jsTxt_FunctionStartDate.Value = jsTxt_FunctionStartDate.MinDate;
        //jsTxt_FunctionEndDate.Value = jsTxt_FunctionEndDate.MaxDate;
    }

    protected void btn_UpdateFunc_Click(object sender, EventArgs e)
    {
        if (HF_RowIndex.Value != String.Empty && Page.IsValid)
        {
            //int selectedRowIndex = Convert.ToInt32(HF_RowIndex.Value);

            List<ViewZTWFunction> pagefuncList = (ViewState["PageFuncs"] == null ? new List<ViewZTWFunction>() : (ViewState["PageFuncs"] as List<ViewZTWFunction>));

            ViewState["PageFuncs"] = generatePageFunctions(pagefuncList,
                pagefuncList[Convert.ToInt32(HF_RowIndex.Value)], false, ddl_Functie, chk_Transport,
                ddl_Activiteit, ddl_Klasse, ddl_timeUnit, ddl_IndicationType, txt_Number,
                jsTxt_FunctionStartDate, jsTxt_FunctionEndDate);

            gv_Functions.DataSource = pagefuncList;
            gv_Functions.DataBind();

            //foreach (TableCell extc in gv_Functions.Rows[selectedRowIndex].Cells)
            //{
            //    extc.BackColor = System.Drawing.ColorTranslator.FromHtml("#C1DAD7");
            //}
            btn_UpdateFunc.Enabled = false;
            btn_AddFunc.Enabled = true;

            ResetFunctionInputs();
        }
    }

    /// <summary>
    /// Generated the page functions List
    /// </summary>
    /// <param name="pagefuncList"></param>
    /// <param name="pagefunc"></param>
    /// <param name="addMethod">True: adding; False: updating;</param>
    /// <returns></returns>
    private List<ViewZTWFunction> generatePageFunctions(List<ViewZTWFunction> pagefuncList,
        ViewZTWFunction pagefunc, bool addMethod, DropDownList page_ddl_Functie, CheckBox page_chk_Transport,
        DropDownList page_ddl_Activiteit, DropDownList page_ddl_Klasse, DropDownList page_ddl_timeUnit, DropDownList page_ddl_IndicationType,
        TextBox page_txt_Number, TextBox page_WDC_Ingangsdatum, TextBox page_WDC_Endiedatum)
    {
        pagefunc.Functiecode = new CodelijstGegeven(page_ddl_Functie.SelectedValue,
            page_ddl_Functie.SelectedItem.Text.Replace("-", String.Empty).Replace(page_ddl_Functie.SelectedValue, String.Empty).ToString().Trim(), String.Empty);

        if (pagefunc.Functiecode.Code == "12" || pagefunc.Functiecode.Code == "52" || pagefunc.Functiecode.Code == "82")
        {
            pagefunc.IndicatieVervoer = page_chk_Transport.Checked ? "1" : "2";
        }

        pagefunc.GewensteStartdatum = DateTime.Parse(page_WDC_Ingangsdatum.Text.Trim());
        pagefunc.GewensteEinddatum = DateTime.Parse(page_WDC_Endiedatum.Text.Trim());

        List<CodelijstGegeven> active = new List<CodelijstGegeven>();
        active.Add(new CodelijstGegeven(page_ddl_Activiteit.SelectedValue, String.Empty,
            page_ddl_Activiteit.SelectedItem.Text.Replace("-", String.Empty).Replace(page_ddl_Activiteit.SelectedValue, String.Empty).ToString().Trim()));
        pagefunc.Activiteiten = active;

        pagefunc.KlasseCode = new CodelijstGegeven(page_ddl_Klasse.SelectedValue,
            page_ddl_Klasse.SelectedItem.Text.Replace("-", String.Empty).Replace(page_ddl_Klasse.SelectedValue, String.Empty).ToString().Trim(), String.Empty);

        if (page_txt_Number.Text.ToString().Trim() != String.Empty)
        {
            pagefunc.AantalOmgvangOpslagKlasse = page_txt_Number.Text.ToString().Trim();
            pagefunc.TijdseenheidZorgperiode = new CodelijstGegeven(page_ddl_timeUnit.SelectedValue, page_ddl_timeUnit.SelectedItem.Text.ToString().Trim());
        }

        pagefunc.Leveringsvorm = new CodelijstGegeven(page_ddl_IndicationType.SelectedValue,
            page_ddl_IndicationType.SelectedItem.Text.Replace("-", String.Empty).Replace(page_ddl_IndicationType.SelectedValue, String.Empty).ToString().Trim(), String.Empty);

        if (addMethod) { pagefuncList.Add(pagefunc); }

        //pagefunc.FunctionZZPType = funcZZPType;

        return pagefuncList;
    }

    protected void functions_btn_Previous_Click(object sender, EventArgs e)
    {
        LoadStepPage(StepType.Step3);
    }

    protected void btn_ResetSelected_Click(object sender, EventArgs e)
    {
        if (btn_UpdateFunc.Enabled)
        {
            GridViewRow gvr = gv_Functions.Rows[Convert.ToInt32(HF_RowIndex.Value)];

            if (gvr.Enabled)
            {
                foreach (TableCell extc in gvr.Cells)
                {
                    extc.BackColor = System.Drawing.Color.White;
                }
            }

            HF_RowIndex.Value = String.Empty;
            HF_ZZPID.Value = String.Empty;

            ddl_Functie.Enabled = true;
            btn_AddFunc.Enabled = true;
            btn_UpdateFunc.Enabled = false;
        }
    }
    #endregion

    #region GridView Actions
    //private void LoadStep4SourceDatas()
    //{
    //    using (Indicatiebesluit indi = (Indicatiebesluit)ViewState["PAGEINDICATION"])
    //    {
    //        firstZZP_head.Visible = chk_AdditionalZZPs.Checked;
    //        div_secondZZP.Visible = chk_AdditionalZZPs.Checked;
    //    }
    //}

    protected void gv_Functions_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && gv_Functions.Enabled)
        {
            for (var i = 1; i < e.Row.Cells.Count; i++)
            {
                if (e.Row.Cells[17].Text.Replace("&nbsp;", String.Empty).ToString().Trim().Length > 1)
                {
                    e.Row.Enabled = getIsTransportByFunction(e.Row.Cells[10].Text.Replace("&nbsp;", String.Empty).ToString());

                    if (e.Row.Enabled)
                    {
                        SetRowStatusbyTransport(i, sender, e);
                        e.Row.Cells[0].Enabled = false;
                    }
                    else
                    {
                        e.Row.Cells[i].BackColor = System.Drawing.Color.WhiteSmoke;
                    }

                    ((ImageButton)e.Row.Cells[0].FindControl("ImageButton1")).ImageUrl = "../../../img/emptySign.gif";
                }
                else
                {
                    SetRowStatusbyTransport(i, sender, e);
                }
            }

            if (e.Row.Cells[7].Text == @"04")
            { e.Row.Cells[7].Text = @"Uren"; }

            if (e.Row.Cells[7].Text == @"13")
            { e.Row.Cells[7].Text = @"Dagdelen"; }

            HF_RowIndex.Value = String.Empty;
        }
    }

    private void SetRowStatusbyTransport(int i, object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[i].Attributes["OnClick"] = ClientScript.GetPostBackEventReference((GridView)sender, "Select$" + e.Row.RowIndex);
        e.Row.Cells[i].Style["cursor"] = "hand";

        e.Row.Cells[i].Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#C1DAD7'");
        e.Row.Cells[i].Attributes.Add("onmouseout", "this.style.backgroundColor=c");

        e.Row.Cells[0].Style["cursor"] = "hand";
    }

    protected void gv_Functions_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        List<ViewZTWFunction> pagefuncList = (List<ViewZTWFunction>)ViewState["PageFuncs"];

        pagefuncList.RemoveAt(e.RowIndex);

        gv_Functions.DataSource = pagefuncList;
        gv_Functions.DataBind();

        //if (HF_RowIndex.Value != String.Empty)
        //{
        btn_AddFunc.Enabled = true;
        btn_UpdateFunc.Enabled = false;
        ddl_Functie.Enabled = true;

        HF_RowIndex.Value = String.Empty;
        ResetFunctionInputs();
    }

    protected void gv_Functions_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (GridViewRow gvFuncSRow = ((GridView)sender).SelectedRow)
        {
            SetSelectedFunctionValues(gvFuncSRow, jsTxt_FunctionStartDate, jsTxt_FunctionEndDate,
                        ddl_Functie, chk_Transport, ddl_Activiteit, ddl_Klasse, ddl_timeUnit, txt_Number, ddl_IndicationType,
                        btn_AddFunc, btn_UpdateFunc);

            foreach (GridViewRow gvr in gv_Functions.Rows)
            {
                if (gvr.Enabled)
                {
                    foreach (TableCell extc in gvr.Cells)
                    {
                        extc.BackColor = gvr.RowIndex != gvFuncSRow.RowIndex ? System.Drawing.Color.White : System.Drawing.ColorTranslator.FromHtml("#C1DAD7");
                    }
                }
            }

            HF_RowIndex.Value = gvFuncSRow.RowIndex.ToString();
            HF_ZZPID.Value = gvFuncSRow.Cells[17].Text.ToString().Replace("&nbsp;", String.Empty);
        }
    }

    private Boolean? getIsTransport(String gridValue)
    {
        Boolean? result = null;

        if (gridValue.Length != 0)
        {
            result = gridValue == "1" ? true : false;
        }

        return result;
    }

    private Boolean getIsTransportByFunction(String functionCode)
    {
        return (functionCode == "12" || functionCode == "52" || functionCode == "82") ? true : false;
    }

    private void SetSelectedFunctionValues(GridViewRow gv_FuncSRow, TextBox page_WDC_Ingangsdatum, TextBox page_WDC_Endiedatum,
        DropDownList page_ddl_Functie, CheckBox page_chk_Transport, DropDownList page_ddl_Activiteit, DropDownList page_ddl_Klasse, DropDownList page_ddl_timeUnit,
        TextBox page_txt_Number, DropDownList page_ddl_IndicationType, Button page_btn_AddFunc, Button page_btn_UpdateFunc)
    {
        page_ddl_Functie.Enabled = false;

        if (new Guid(gv_Functions.DataKeys[gv_FuncSRow.RowIndex].Value.ToString()) == new Guid())
        {
            changeInputStatusSelectedAddingFunc(gv_FuncSRow, page_WDC_Ingangsdatum, page_WDC_Endiedatum,
                                                page_ddl_Functie, page_chk_Transport, page_ddl_Activiteit,
                                                page_ddl_Klasse, page_ddl_timeUnit, page_txt_Number);
        }
        else
        {
            ChangeStep4InputsStatus(false, page_WDC_Ingangsdatum, page_WDC_Endiedatum,
                                    page_ddl_Functie, page_ddl_Activiteit, page_ddl_Klasse, page_ddl_timeUnit,
                                    page_txt_Number);
        }

        if (gv_FuncSRow.Cells[17].Text.Replace("&nbsp;", String.Empty).ToString().Trim().Length > 1)
        {
            //Boolean  getIsTransportByFunction(gv_FuncSRow.Cells[10].Text.Replace("&nbsp;", String.Empty).ToString());

            ChangeStep4InputsStatus(false, page_WDC_Ingangsdatum, page_WDC_Endiedatum,
                                    page_ddl_Functie, page_ddl_Activiteit, page_ddl_Klasse, page_ddl_timeUnit,
                                    page_txt_Number);

            ddl_IndicationType.Enabled = false;
        }


        page_ddl_IndicationType.SelectedValue = gv_FuncSRow.Cells[9].Text == "PGB" ? "2" : "4";
        page_btn_AddFunc.Enabled = false;
        page_btn_UpdateFunc.Enabled = true;

        LoadExtraTimeInputs(gv_FuncSRow.Cells[10].Text.ToString().Trim(), page_ddl_Klasse, lbl_extraTime, page_txt_Number, page_ddl_timeUnit);

        LoadTransport(page_chk_Transport, gv_FuncSRow.Cells[10].Text.ToString().Trim(),
                        getIsTransport(gv_FuncSRow.Cells[16].Text.ToString().Trim()));
    }

    /// <summary>
    /// Set the enabled of the inputs Components of functions (Step 4)
    /// </summary>
    /// <param name="status"></param>
    private void ChangeStep4InputsStatus(Boolean status, TextBox page_WDC_Ingangsdatum, TextBox page_WDC_Endiedatum,
        DropDownList page_ddl_Functie, DropDownList page_ddl_Activiteit, DropDownList page_ddl_Klasse, DropDownList page_ddl_timeUnit,
        TextBox page_txt_Number)
    {
        //page_ddl_Functie.Enabled = status;
        page_WDC_Ingangsdatum.Enabled = status;
        page_WDC_Endiedatum.Enabled = status;
        page_ddl_Activiteit.Enabled = status;
        page_ddl_Klasse.Enabled = status;
        //page_ddl_timeUnit.Enabled = status;
        page_txt_Number.Enabled = status;

        setTextboxDisabledColor(page_txt_Number);
    }

    private void changeInputStatusSelectedAddingFunc(GridViewRow gv_FuncSRow, TextBox page_WDC_Ingangsdatum, TextBox page_WDC_Endiedatum,
        DropDownList page_ddl_Functie, CheckBox page_chk_Transport, DropDownList page_ddl_Activiteit, DropDownList page_ddl_Klasse, DropDownList page_ddl_timeUnit,
        TextBox page_txt_Number)
    {
        ChangeStep4InputsStatus(true, page_WDC_Ingangsdatum, page_WDC_Endiedatum,
                page_ddl_Functie, page_ddl_Activiteit, page_ddl_Klasse, page_ddl_timeUnit, page_txt_Number);

        page_WDC_Ingangsdatum.Text = getGridviewRowData(gv_FuncSRow, "lbl_startDate");
        page_WDC_Endiedatum.Text = getGridviewRowData(gv_FuncSRow, "lbl_endDate");

        page_ddl_Functie.SelectedValue = gv_FuncSRow.Cells[10].Text;

        if (page_ddl_Functie.SelectedValue == "12" || page_ddl_Functie.SelectedValue == "52" || page_ddl_Functie.SelectedValue == "82")
        {
            page_chk_Transport.Checked = gv_FuncSRow.Cells[16].Text.ToString().Trim() == "1" ? true : false;
        }

        //bindLists(IBManuallyHandler.GetActivies
        //            (page_ddl_Functie.SelectedValue, ((Indicatiebesluit)ViewState["PAGEINDICATION"]).ZZP, nav.User.ConnString),
        //        page_ddl_Activiteit);

        bindLists(IBManuallyHandler.GetActivies(page_ddl_Functie.SelectedValue, null, Nav.User.ConnString), page_ddl_Activiteit);

        bindLists(IBManuallyHandler.GetClasses
                    (page_ddl_Functie.SelectedValue, Nav.User.ConnString),
                page_ddl_Klasse);

        page_ddl_Activiteit.SelectedValue = gv_FuncSRow.Cells[11].Text;
        page_ddl_Klasse.SelectedValue = gv_FuncSRow.Cells[12].Text;

        if (getGridviewRowData(gv_FuncSRow, "lbl_number").ToString().Trim() != String.Empty)
        {
            page_txt_Number.Text = getGridviewRowData(gv_FuncSRow, "lbl_number");

            if (getGridviewRowData(gv_FuncSRow, "lbl_timeUnit") == "Uren")
            {
                page_ddl_timeUnit.SelectedValue = "04";
            }

            if (getGridviewRowData(gv_FuncSRow, "lbl_timeUnit") == "Dagdelen")
            {
                page_ddl_timeUnit.SelectedValue = "13";
            }
        }
        else
        {
            page_txt_Number.Text = String.Empty;
            page_ddl_timeUnit.SelectedIndex = -1;
        }
    }
    #endregion

    #endregion

    #region Save datas button Action
    protected void functions_btn_Cancel_Click(object sender, EventArgs e)
    {
        //ModalPopupFunction(functions_btn_Cancel.ID);
        //gv_Functions.DataSource = ViewState["PageFuncs"];
        //gv_Functions.DataBind();

        //SetFunctionButtons(PanelType.firstP);
        //SetFunctionButtons(PanelType.secondP);
        //secure_zk_PGB_Assignment_AddIB_FunctionInputs ucFunc = new secure_zk_PGB_Assignment_AddIB_FunctionInputs();

        //ucFunc.ChangeStep4InputsStatus(true);
        //LoadStep4SourceDatas();
        CancelBacktoStep1();
    }

    private List<ViewZTWFunction> getPageFunctions(Indicatiebesluit pageIndication, List<ViewZTWFunction> pageFuncs)
    {
        foreach (ViewZTWFunction ztwF in pageFuncs)
        {
            ztwF.NewZTWFunctionID = Guid.NewGuid();
            ztwF.IndicationID = pageIndication.IndicatiebesluitID;
            ztwF.UpdatedBy = new Guid(Nav.User.UserID);
        }

        return pageFuncs;
    }

    private Adres generatePageAdres()
    {
        Adres pAddress = null;

        if (HF_AddressID.Value.Length != 0)
        {
            pAddress = new Adres();
            pAddress.AdresID = new Guid(HF_AddressID.Value);
            //pAddress.SoortAdres = new CodelijstGegeven(soortadres.Waarde);
            pAddress.SoortAdres = ((Adres)ViewState["OrignalAddress"]).SoortAdres;

            if (huisnummer.Waarde.Trim().ToString().Length != 0)
            {
                pAddress.Huisnummer = Convert.ToInt32(huisnummer.Waarde.Trim().ToString());
            }

            pAddress.HuisnummerToevoeging = huisnummertoevoeging.Waarde.Trim();
            pAddress.Postcode = postcode.Waarde.Trim();
            pAddress.Straatnaam = straatnaam.Waarde.Trim();
            pAddress.WoonplaatsNaam = woonplaats.Waarde.Trim();
            pAddress.CodeLand = codeland.Waarde.Trim();
            pAddress.Telefoonnummer01 = telefoonnummer1.Waarde.Trim();

            if (new Guid(Convert.ToString(Session["ClientID"])) == new Guid() || ((Adres)ViewState["OrignalAddress"]).IsPostAdres)
            {
                pAddress.IsPostAdres = true;
            }

            if (pAddress.Equals((Adres)ViewState["OrignalAddress"]))
            {
                pAddress = (Adres)ViewState["OrignalAddress"];
            }
        }
        else if (huisnummer.Waarde != String.Empty &&
            postcode.Waarde != String.Empty &&
            straatnaam.Waarde != String.Empty &&
            woonplaats.Waarde != String.Empty)
        {
            pAddress = new Adres();
            pAddress.SoortAdres = new CodelijstGegeven(soortadres.Waarde);

            if (huisnummer.Waarde.Trim().ToString().Length != 0)
            {
                pAddress.Huisnummer = Convert.ToInt32(huisnummer.Waarde.Trim().ToString());
            }

            pAddress.HuisnummerToevoeging = huisnummertoevoeging.Waarde.Trim();
            pAddress.Postcode = postcode.Waarde.Trim();
            pAddress.Straatnaam = straatnaam.Waarde.Trim();
            pAddress.WoonplaatsNaam = woonplaats.Waarde.Trim();
            pAddress.CodeLand = codeland.Waarde.Trim();
            pAddress.Telefoonnummer01 = telefoonnummer1.Waarde.Trim();

            if (new Guid(Convert.ToString(Session["ClientID"])) == new Guid())
            {
                //pAddress.IsPostAdres = true;
                pAddress.IsPostAdres = false;
            }
        }

        return pAddress;
    }

    #region Check the insuranceCompany
    /// <summary>
    /// It should be checked after the adding part;
    /// </summary>
    private void CheckInsuranceCompany(Client client)
    {
        Boolean COVControl = false;
        //if (client.Verzekerdennummer != Verzekerdenummer.Waarde.Trim() || client.UZOVInummer != UZOVInummer.Waarde.Trim())
        if (client.Verzekerdennummer != Verzekerdenummer.Waarde.Trim())
        {
            COVControl = true;
        }

        String oldUzovi = client.UZOVInummer;

        if (COVControl)
        {
            //IBManuallyHandler.COVControleUitvoeren(client, oldUzovi, COVControl);
        }
    }
    #endregion

    protected void btn_Save_Click(object sender, EventArgs e)
    {
        Boolean addStatus = (ViewState["PageClient"] as Client).ClientID == new Guid() ? true : false;

        try
        {
            if (gv_Functions.Rows.Count > 0)
            {
                Indicatiebesluit pageIndi = (Indicatiebesluit)ViewState["PAGEINDICATION"];
                List<ViewZTWFunction> pageFunc = getPageFunctions(pageIndi, (List<ViewZTWFunction>)ViewState["PageFuncs"]);

                IBManuallyHandler ibm = new IBManuallyHandler();
                ibm.processManuallyIBDatas((ViewState["PageClient"] as Client),
                    (Adres)ViewState["PageAddress"], (Adres)ViewState["OrignalAddress"],
                    pageFunc, pageIndi, (List<IBZZP>)ViewState["PAGEIBZZPS"], (List<ZTWZZP>)ViewState["PAGEZTWZZPS"], Nav.User.ZorgkantoorID, Nav.User.ConnString, Nav.User.UserID, Nav.User.BestandenDbConnString, Nav.User.Zorgkantoorcode, Nav.User.UserName,
                    ViewState["BIRTHDAYCHANGED"] == null ? false : (Boolean)ViewState["BIRTHDAYCHANGED"]);
                Client client = ViewState["PageClient"] as Client;
                //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "IB Adding", "parent.resultaat.location.href = 'CheckBSN.aspx'", true);
                Nav.HoofdNavigatie = EHoofdNavigatie.Clienten;
                Nav.SubNavigatie = ESubNavigatie.PGBOverzicht;
                Nav.Client = client;
                Session["Navigatie"] = Nav;
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Clienten", "GrootFrame();parent.overview.location.href = '../../../ClientenOverzicht.aspx?type=client&clientID=" + client.ClientID.ToString() + "';", true);
            }
        }
        catch (ClientBedrijfsregelfout ex)
        {
            if (addStatus)
            {
                (ViewState["PageClient"] as Client).ClientID = new Guid();
            }
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "fouten", "<script>alert('" + ex.Message + "')</script>");
        }
        catch (AdresBedrijfsregelfout ex)
        {
            if (addStatus)
            {
                (ViewState["PageClient"] as Client).ClientID = new Guid();
            }
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "fouten", "<script>alert('" + ex.Message + "')</script>");
        }
    }
    #endregion
}
